<!--
@description    绩效报表-双向评分
@author         秦俊强
@email          458112865@qq.com
@create         2020-02-18 18:00
-->

<template>
  <div class="ant-card ant-card-body">

    <!-- 菜单区 start -->
    <div class="menu-box">
      <div class="query-date">
        <span>考核期：</span>
        <a-select v-if="!yearMonthList.loading"
                  :value="yearMonthList.val.text"
                  @change="changeDate">
          <a-select-option v-for="date in yearMonthList.arr"
                           :key="date.value">{{ date.text }}</a-select-option>
        </a-select>
        <a-select v-else :defaultValue="'数据加载中'" disabled></a-select>
      </div>

      <div class="query-target">
        <span>评分指标：</span>
        <a-select mode="multiple" placeholder="全部指标"
                  :allowClear="true" :maxTagCount="0"
                  :dropdownMatchSelectWidth="false"
                  :showArrow="true"
                  @change="targetChange">
          <a-select-option v-for="target in targetInfo.arr"
                           :key="target.code"
                           :title="target.name">{{ target.name }}</a-select-option>
        </a-select>
      </div>

      <div style="margin: 5px">
        <span>注意：双向评分需在每月1号-10号完成</span>

      </div>
    </div>
    <!-- 菜单区 end -->


    <!-- 内容区 start -->
    <div class="content-box">

      <div class="view-box">
        <a-table :loading="tableData.loading"
                 :scroll="tableData.scroll"
                 :columns="tableData.columns"
                 :dataSource="tableData.dataSource"
                 :pagination="false">

          <!-- 评分 start -->
          <template :slot="'scoreValue'" slot-scope="text, record, ind">
            <div v-if="record.isEditScore">
              <a-input class="edit-input" type="number" :ref="'editInput-' + ind"
                       :value="editRowScore.scoreValue"
                       @change="handleChange($event)"
                       @pressEnter="checked(ind)" />

              <a-icon type="check" class="editable-cell-icon-check"
                      title="确定" @click="checked(ind)" />
              <a-icon type="close" class="editable-cell-icon-cancel"
                      title="取消" @click="switchScoreArr()" />
            </div>

            <!-- <div @click="switchScoreArr(ind)" style="cursor: pointer;" v-else> -->
              <!-- 移植操作事件 -->
            <div @click="switchEditPop(true, record)" style="cursor: pointer;" v-else>

              <span>{{ text }}</span>
              <a-icon type="edit" class="editable-cell-icon" title="编辑" />
            </div>
          </template>
          <!-- 评分 end -->

          <!-- 意见 start -->
          <template :slot="'scoreComments'" slot-scope="text, record, ind">
            <div class="comments-box" v-for="(item, index) in text " :key="index">
              <span v-if="text.length > 1">{{ index + 1 }}. </span>
              <span :title="item.title">{{ item.title }}</span>

              <a-tooltip placement="right" :title="item.content">
                <a-icon class="icon-more" type="message"></a-icon>
              </a-tooltip>
            </div>
          </template>
          <!-- 意见 end -->

          <!-- 编辑 start -->
          <!-- <template :slot="'operation'" slot-scope="text, record, ind">
            <span class="btn-edit" @click="switchEditPop(true, record)">评分意见</span>
          </template> -->
          <!-- 编辑 end -->

        </a-table>
      </div>


      <!-- 分页器 start -->
      <div class="pagination-box">
        <a-pagination :current="pageData.pageNo"
                      :pageSize="pageData.pageSize"
                      :total="pageData.total"
                      :pageSizeOptions="['10', '20', '30']"
                      @change="changePage"
                      showSizeChanger
                      @showSizeChange="onShowSizeChange"  />
      </div>
      <!-- 分页器 end -->
    </div>
    <!-- 内容区 end -->


    <!-- 弹窗编辑 start -->
    <a-modal v-model="modalInfo.show"
             :title="modalInfo.title"
             :maskClosable="false"
             :width="'800px'" :destroyOnClose="true" @ok="saveComment">
      <div class="loading-box" v-if="modalInfo.loading">
        <a-icon class="icon-loading" type="loading" />
      </div>
      <EditScoreComments :editData="modalInfo.date" :show="modalInfo.show" :differentiate="modalInfo.differentiate"
                         :date="yearMonthList.val.text"></EditScoreComments>
    </a-modal>
    <!-- 弹窗编辑 end -->
  </div>
</template>



<script>

  /* 引入表格配置文件 */
  import { tableConfig } from './configs/table.score.config.js';

  /* 封装通用 api 服务 */
  import { apiService } from '@/api/api.service.js';

  /**
   * api 接口
   *
   * getYearMonthList => 获取评分年月信息
   * getScoreIndexCodes => 获取指标下拉菜单
   * _getScoreDatagrid => 获取双向评分列表
   * saveScoreComment => 保存意见
   * saveScoreValue => 保存评分
   * */
  import {
    getYearMonthList, getScoreIndexCodes, _getScoreDatagrid,
    saveScoreComment, saveScoreValue
  } from '@/api/api.js';

  /* 引入通用表格组件 */
  import EditScoreComments from './components/EditScoreComments';




  export default {
    components: { EditScoreComments },

    data() {
      return {
        /* 考核期 */
        yearMonthList: {
          loading: true,
          arr: [],
          val: {}
        },

        /* 评分指标 */
        targetInfo: {
          loading: true,
          arr: [],
          indexs: []
        },

        /* 表格参数 */
        tableData: tableConfig(),

        /* 分页 */
        pageData: {
          pageNo: 1,
          pageSize: 10,
          total: 1
        },

        /* 弹窗信息 */
        //differentiate用于角色区分  申嘉文（kpi）  2   孙毅，葛明 0  纪琼霄（gm）  1
        modalInfo: {
          show: false,
          title: '编辑',
          loading: false,
          date: {},
          differentiate:0
        },

        /* 当前编辑的行数据 */
        editRowScore: {},

        /* 用于延时调用搜索接口 */
        timeout: null
      }
    },

    created() {
      this.getYearMonthList();      // 获取评分年月
      this.getScoreIndexCodes();    // 获取指标下拉菜单
    },

    methods: {

      /* 切换状态 */
      switchScoreArr(ind) {
        let arr = [];
        for (let i = 0; i < this.tableData.dataSource.length; i++) {
          let item = this.tableData.dataSource[i];
          if (typeof ind === 'undefined') {
            delete item.isEditScore;
          } else {
            if (i === ind) {
              item['isEditScore'] = true;
              this.editRowScore = JSON.parse(JSON.stringify(item));
            } else {
              item['isEditScore'] = false;
            }
          }
          arr.push(item);
        }

        this.tableData.dataSource = arr;

        setTimeout(() => {
          // 鼠标光标聚焦
          let ref = this.$refs['editInput-' + ind];
          ref && ref.focus();
        }, 100);
      },

      /* 监听评分值的改变 */
      handleChange(e) {
        let value = e.target.value;

        // 不允许输入小数
        if (value.indexOf('.') >= 0) {
          this.editRowScore.scoreValue = value.split('.')[0];
          this.$message.warning('不允许输入小数！');
          return;
        }

        if (value.indexOf('0') === 0 && value.length >= 2 || value.indexOf('-0') === 0 && value.length >= 3) {
          this.editRowScore.scoreValue = '0';
          return;
        }

        // 评分数值限制最大 10 分
        if (value > 10) {
          this.editRowScore.scoreValue = 10;
          this.$message.warning('最大分数为 10 分！');
          return;
        }

        // 评分数值限制最小 (-10) 分
        if (value < (-10)) {
          this.editRowScore.scoreValue = -10;
          this.$message.warning('评分分数不能小于 -10！');
          return;
        }

        this.editRowScore.scoreValue = value;
      },

      /* 监听考核期变化 */
      changeDate(code) {
        let arr = this.yearMonthList.arr;
        this.yearMonthList.val = arr.find((item) => { return (item.value === code); });
        this.getData();
      },

      /* 监听考核指标变化 */
      targetChange(codes) {
        clearTimeout(this.timeout);     // 清除定时器

        this.targetInfo.indexs = codes;
        this.pageData.pageNo = 1;
        this.timeout = setTimeout(() => { this.getData(); }, 1300);
      },

      /* 监听分页页数的变化 */
      changePage(pageNo) {
        this.pageData.pageNo = pageNo;
        this.getData();
      },

      /* 监听分页条数的变化 */
      onShowSizeChange(current, pageSize) {
        this.pageData.pageSize = pageSize;
        this.pageData.pageNo = 1;
        this.getData();
      },

      /* 弹窗编辑 */
      switchEditPop(b, obj) {
        this.modalInfo.date = JSON.parse(JSON.stringify(obj));
        this.modalInfo.loading = false;
        this.modalInfo.show = true;
      },

      /* 保存分数 */
      checked(ind) {
        let editRowScore = this.editRowScore;
        let param = {
          "indexYearMonth": this.yearMonthList.val.value,
          "values": [{
            "indexCode": editRowScore.indexCode,
            "indexValueCode": editRowScore.indexValueCode,
            "indexDepart": editRowScore.indexOrgCode,
            "scorerCode": editRowScore.scorerCode,
            "scoreValue": editRowScore.scoreValue
          }]
        }
        this.tableData.loading = true;
        apiService(saveScoreValue(param)).then((res) => {
          this.tableData.loading = false;
          if (!res.success) {
            this.$message.error(res.message);
            return;
          }

          this.tableData.dataSource[ind] = this.editRowScore;
          this.switchScoreArr();
        }).catch((error) => {
          this.tableData.loading = false;
          this.$message.error(error.message);
        });
      },

      /* 保存意见 */
      saveComment() {
        let data = this.modalInfo.date;
        if(data.scoreValue===''){
          this.$message.warning('评分不能为空！请合法打分');
          return;
        }
        if(data.scoreComments.length<=0){
          if(data.scoreValue!=0){
            this.$message.warning('必须添加评分事项！');
            return;
          }
        }
        if(data.scoreComments.length>=0 && data.scoreValue!=0){
          for (let i in data.scoreComments) {
            if(data.scoreComments[i].code===''){
              this.$message.warning('评分事项不能为空！');
              return;
            }else if(data.scoreComments[i].content===''){
              this.$message.warning('评分意见不能为空！');
              return;
            }
          }
        }else {
          for (let i in data.scoreComments) {
            if (data.scoreComments[i].code === '' && data.scoreComments[i].content === '') {
              data.scoreComments.splice(i)          }
          }
        }


          let param = {
            "indexYearMonth":  this.yearMonthList.val.value,
            "indexValueCode": data.indexValueCode,
            "indexDepart": data.indexOrgCode,
            "scorerCode": data.scorerCode,
            "scoreValue": data.scoreValue,
            "scoreComments": [...data.scoreComments]
          }

        this.modalInfo.loading = true;
        apiService(saveScoreComment(param)).then((res) => {
          this.modalInfo.loading = false;
          this.modalInfo.show = false;
          this.getData();
        }).catch((error) => {
          this.modalInfo.loading = false;
          this.$message.error(error.message);
        });
      },

      /* 获取列表信息 */
      getData() {
        let param = {
          indexOrgs: [],    // 查询所有机构
          indexYearMonth: this.yearMonthList.val.value,   // 考核年月
          indexCodes: this.targetInfo.indexs,             // 评分指标
          pageNo: this.pageData.pageNo,
          pageSize: this.pageData.pageSize
        };

        this.tableData.loading = true;
        apiService(_getScoreDatagrid(param)).then((res) => {
          this.tableData.loading = false;
          let result = res.result;
          this.tableData.dataSource = result.records;
          this.pageData.total = result.total;
        }).catch((error) => {
          this.tableData.loading = false;
          this.$message.error(error.message);
        });
      },

      /* 获取年月下拉菜单 */
      getYearMonthList() {
        this.yearMonthList.loading = true;
        apiService(getYearMonthList()).then((res) => {
          let list = res.result || [];
          this.yearMonthList = {
            loading: false,
            arr: list,
            val: list[0]
          };

          this.getData();
        }).catch((error) => {
          this.yearMonthList.loading = false;
          this.$message.error(error.message);
        });
      },

      /* 获取指标下拉菜单 */
      getScoreIndexCodes() {
        this.targetInfo.loading = true;
        apiService(getScoreIndexCodes()).then((res) => {
          this.targetInfo.loading = false;
          this.targetInfo.arr = res.result || [];
        }).catch((error) => {
          this.targetInfo.loading = false;
          this.$message.error(error.message);
        });
      }
    }
  }
</script>





<style lang="less" scoped>
  .menu-box {
    overflow: hidden;
    margin-bottom: 10px;

    [class*="query-"] {
      float: left;
      margin-right: 10px;
    }

    /deep/.ant-select {
      width: 120px;
    }

    .query-depart {
      /deep/.ant-select {
        width: 180px;
      }
    }
  }

  .content-box {

    .icon-more {
      margin-left: 5px;
      color: @primary-color;
    }

    .btn-edit {
      color: @primary-color;
      cursor: pointer;

      &:hover {
        text-decoration: underline;
      }
    }

    .editable-cell-icon,
    .editable-cell-icon-check,
    .editable-cell-icon-cancel {
      margin-left: 5px;
    }

    .editable-cell-icon { color: #FA541C; }
    .editable-cell-icon-check { color: #1890FF; }
    .editable-cell-icon-cancel { color: #808080; }

    .edit-input {
      padding: 0 5px;
      width: 90px;
    }

    /deep/.ant-table-tbody > tr > td {
      min-height: 40px;
      padding-top: 5px;
      padding-bottom: 5px;
      text-align: right  !important;

      input { height: 30px; }
    }

    .comments-box {
      text-align: left;
      margin-bottom: 5px;
    }
  }

  .pagination-box {
    margin-top: 20px;
    float: right;
  }

  .loading-box {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 100;
    background: rgba(255, 255, 255, 0.4);
    text-align: center;
    padding-top: 35%;
  }
</style>
